/*
 * @Author: shenya shenya0203@163.com
 * @Date: 2024-03-23 16:01:36
 * @LastEditors: shenya shenya0203@163.com
 * @LastEditTime: 2024-03-26 10:47:04
 * @FilePath: /code/src/protocol_data.c
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include "protocol_data.h"
#include "json_data.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// base64 转换表, 共64个
static const char base64_alphabet[] = {
    'A', 'B', 'C', 'D', 'E', 'F', 'G',
    'H', 'I', 'J', 'K', 'L', 'M', 'N',
    'O', 'P', 'Q', 'R', 'S', 'T',
    'U', 'V', 'W', 'X', 'Y', 'Z',
    'a', 'b', 'c', 'd', 'e', 'f', 'g',
    'h', 'i', 'j', 'k', 'l', 'm', 'n',
    'o', 'p', 'q', 'r', 's', 't',
    'u', 'v', 'w', 'x', 'y', 'z',
    '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
    '+', '/'};

// 解码时使用
static const unsigned char base64_suffix_map[256] = {
    255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 253, 255,
    255, 253, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
    255, 255, 255, 255, 255, 255, 255, 255, 253, 255, 255, 255,
    255, 255, 255, 255, 255, 255, 255, 62, 255, 255, 255, 63,
    52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 255, 255,
    255, 254, 255, 255, 255, 0, 1, 2, 3, 4, 5, 6,
    7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
    19, 20, 21, 22, 23, 24, 25, 255, 255, 255, 255, 255,
    255, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36,
    37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
    49, 50, 51, 255, 255, 255, 255, 255, 255, 255, 255, 255,
    255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
    255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
    255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
    255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
    255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
    255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
    255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
    255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
    255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
    255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
    255, 255, 255, 255};

static char cmove_bits(unsigned char src, unsigned lnum, unsigned rnum)
{
    src <<= lnum; // src = src << lnum;
    src >>= rnum; // src = src >> rnum;
    return src;
}

int base64_encode1(const char *indata, int inlen, char *outdata, int *outlen)
{

    int ret = 0; // return value
    if (indata == NULL || inlen == 0)
    {
        return ret = -1;
    }

    int in_len = 0;  // 源字符串长度, 如果in_len不是3的倍数, 那么需要补成3的倍数
    int pad_num = 0; // 需要补齐的字符个数, 这样只有2, 1, 0(0的话不需要拼接, )
    if (inlen % 3 != 0)
    {
        pad_num = 3 - inlen % 3;
    }
    in_len = inlen + pad_num; // 拼接后的长度, 实际编码需要的长度(3的倍数)

    int out_len = in_len * 8 / 6; // 编码后的长度

    char *p = outdata; // 定义指针指向传出data的首地址

    // 编码, 长度为调整后的长度, 3字节一组
    for (int i = 0; i < in_len; i += 3)
    {
        int value = *indata >> 2;        // 将indata第一个字符向右移动2bit(丢弃2bit)
        char c = base64_alphabet[value]; // 对应base64转换表的字符
        *p = c;                          // 将对应字符(编码后字符)赋值给outdata第一字节

        // 处理最后一组(最后3字节)的数据
        if (i == inlen + pad_num - 3 && pad_num != 0)
        {
            if (pad_num == 1)
            {
                *(p + 1) = base64_alphabet[(int)(cmove_bits(*indata, 6, 2) + cmove_bits(*(indata + 1), 0, 4))];
                *(p + 2) = base64_alphabet[(int)cmove_bits(*(indata + 1), 4, 2)];
                *(p + 3) = '=';
            }
            else if (pad_num == 2)
            { // 编码后的数据要补两个 '='
                *(p + 1) = base64_alphabet[(int)cmove_bits(*indata, 6, 2)];
                *(p + 2) = '=';
                *(p + 3) = '=';
            }
        }
        else
        { // 处理正常的3字节的数据
            *(p + 1) = base64_alphabet[cmove_bits(*indata, 6, 2) + cmove_bits(*(indata + 1), 0, 4)];
            *(p + 2) = base64_alphabet[cmove_bits(*(indata + 1), 4, 2) + cmove_bits(*(indata + 2), 0, 6)];
            *(p + 3) = base64_alphabet[*(indata + 2) & 0x3f];
        }

        p += 4;
        indata += 3;
    }

    if (outlen != NULL)
    {
        *outlen = out_len;
    }

    return ret;
}

int base64_decode1(const char *indata, int inlen, char *outdata, int *outlen)
{

    int ret = 0;
    if (indata == NULL || inlen <= 0 || outdata == NULL || outlen == NULL)
    {
        return ret = -1;
    }
    if (inlen % 4 != 0)
    { // 需要解码的数据不是4字节倍数
        return ret = -2;
    }

    int t = 0, x = 0, y = 0, i = 0;
    unsigned char c = 0;
    int g = 3;

    while (indata[x] != 0)
    {
        // 需要解码的数据对应的ASCII值对应base64_suffix_map的值
        c = base64_suffix_map[indata[x++]];
        if (c == 255)
            return -1; // 对应的值不在转码表中
        if (c == 253)
            continue; // 对应的值是换行或者回车
        if (c == 254)
        {
            c = 0;
            g--;
        }                 // 对应的值是'='
        t = (t << 6) | c; // 将其依次放入一个int型中占3字节
        if (++y == 4)
        {
            outdata[i++] = (unsigned char)((t >> 16) & 0xff);
            if (g > 1)
                outdata[i++] = (unsigned char)((t >> 8) & 0xff);
            if (g > 2)
                outdata[i++] = (unsigned char)(t & 0xff);
            y = t = 0;
        }
    }
    if (outlen != NULL)
    {
        *outlen = i;
    }
    return ret;
}

devStateNode_t *devStateList = NULL;

// 创建一个新节点
devStateNode_t *createNode(uint16_t addr, uint16_t dataLen, uint8_t *data)
{
    devStateNode_t *newNode = (devStateNode_t *)malloc(sizeof(devStateNode_t));
    newNode->devState.addr = addr;
    newNode->devState.dataLen = dataLen;
    newNode->devState.data = (uint8_t *)malloc(dataLen);
    if (newNode->devState.data == NULL)
    {
        return NULL; // 分配失败
    }
    memcpy(newNode->devState.data, data, dataLen);

    newNode->next = NULL;
    return newNode;
}

// 插入节点到链表头部
void insertAtBeginning(devStateNode_t **headRef, devStateNode_t **newNode)
{
    (*newNode)->next = *headRef;
    *headRef = *newNode;
}

// 添加节点，addr不重复时创建新节点，重复时，覆盖节点
void addNode(devStateNode_t **headRef, devStateNode_t **newNode)
{
    if (headRef == NULL)
    {
        insertAtBeginning(*headRef, *newNode);
    }
    else
    {
    }
}

// 删除指定节点
void deleteNode(devStateNode_t **headRef, uint16_t key)
{
    devStateNode_t *temp = *headRef, *prev;

    if (temp != NULL && temp->devState.addr == key)
    {
        *headRef = temp->next;
        free(temp);
        return;
    }

    while (temp != NULL && temp->devState.addr != key)
    {
        prev = temp;
        temp = temp->next;
    }

    if (temp == NULL)
        return;

    prev->next = temp->next;
    free(temp);
}

// 打印链表
void printList(devStateNode_t *node)
{
    while (node != NULL)
    {
        printf("%d ", node->devState.addr);
        int i;
        for (i = 0; i < node->devState.dataLen; i++)
        {
            printf("%X ", node->devState.data[i]);
        }
        printf("\n");
        node = node->next;
    }
    printf("\n");
}

// 释放链表内存
void freeList(struct Node **headRef)
{
    struct Node *current = *headRef;
    struct Node *next;

    while (current != NULL)
    {
        next = current->next;
        free(current->devState.data); // 额外增加的
        free(current);
        current = next;
    }
    *headRef = NULL;
}

// 解析数据包
// 结果有
uint8_t reportData_parse(uint8_t *data, uint16_t dataLen, uint16_t *addr)
{
    if (data == NULL)
    {
        return ERRORDATA_DATA_NULL;
    }
    if (!(data[0] == 0x0f && data[1] == 0x00))
    {
        return ERRORDATA_HEAD;
    }
    if (dataLen <= 9) // 避免内存越界
    {
        return ERRORDATA_DATALEN;
    }
    if ((data[5] & 0xf0) == 0xD0) // 网关上报 0xD0类型
    {
        *addr = (data[5] & 0x0f) + data[10];
        printf("ad:%d\n", *addr);
    }
    else if ((data[5] & 0xf0) == 0xC0) // 设备上报
    {
    }
    printf("a..%d\n", data[5]);

    return ERRORDATA_NONE;
}

uint8_t reportData_update(uint8_t *data, uint16_t dataLen)
{
    uint16_t type = 0;
    uint16_t seq = 0;
    uint16_t addr = 0;
    uint8_t *_data = NULL;
    uint16_t _dataLen = 0;
    int ret = 0;
    // ret = reportData_addr(data, dataLen, &addr);
    // if (ret != ERROR_NONE)
    // {
    //     return 1;
    // }

    if (data == NULL)
    {
        return ERRORDATA_DATA_NULL;
    }

    type = (data[1] << 8) | data[0]; // 小端
    seq = (data[3] << 8) | data[2];
    // 解析数据包
    if ((data[5] & 0xf0) == 0xD0) // 网关上报 0xD0类型
    {
        addr = (data[5] & 0x0f) + data[10];
        _dataLen = data[9] >> 4; // 按协议内容，高4位表示实际控制数据长度
        _data = data + 11;
        printf("state update %d\n", addr);
        list_update_stateData(_data, _dataLen, addr); // 11字节为协议具体内容
    }
    else if ((data[5] & 0xf0) == 0xC0) // 设备上报
    {
    }
}
